package com.blackline.auto.Alert;

import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

import com.blackline.auto.common.CommonMethods;
import com.blackline.declareUI.UI;
import com.blackline.parameters.Parameters;
import com.blackline.parameters.TestData;

/**
 * @author XBO
 * @version Jan, 2013
 * <p>The smoke test to Alert module.
 */
public class Alert_smoketest {
	private WebDriver driver;
	private StringBuffer verificationErrors = new StringBuffer();
	private static Logger logger=Logger.getLogger(Alert_smoketest.class);
	UI UI=new UI();
	Parameters parameters;
	@Before
	public void setUp() throws Exception {
		FirefoxProfile profile=new FirefoxProfile();
		profile.setEnableNativeEvents(true);
		parameters=new Parameters("parameters.xml");

		driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		UI.declareAllUI(driver);
	}

	@Test
	public void Alertsmoketest() throws Exception {
		TestData testdata=new TestData("TestData/Alert_smoketest.xml");
		
		//=======================Data Preparation=======================//

		CommonMethods cm = new CommonMethods();
		String dateString = cm.dateString();
		
		//The last field of following inputText is "8900"
		String inputText = "4000	"+ dateString +"									" + dateString+"	"+dateString+"	A	Asset	TRUE	TRUE	USD	USD	1/31/2011			8900";
		logger.info("The inputText for " + testdata.getInput("accountFile") + " is: " + inputText);
		//Create Account.Import.text file and write inputText into it.
		cm.createFile(("TestData\\" + testdata.getInput("accountFile")), inputText);
		
		//The absolute path of the "Alert_Import.Auto01.txt" file.
		String accountFilePath = System.getProperty("user.dir") + "\\TestData\\" + testdata.getInput("accountFile");
		logger.info("Location of " + testdata.getInput("accountFile") + " is: " + accountFilePath);
		
		//Account file without extension, for example: Account_Import.Auto.Match01.txt > Account_Import.Auto.Match01
		String inputFileNoExtension = testdata.getInput("accountFile").substring(0, testdata.getInput("accountFile").length()-4);
		logger.info("Account file without extension is: " + inputFileNoExtension);
	
	//=======================Import Account=======================//
		//Log into system
		UI.LogonPage.Login(driver, parameters.urlDev2, parameters.getLogonID("admin"), parameters.getPassword("admin"));
		//Alert->Alert Schedule
		UI.NavigationMenu.ALERTS.click();
		UI.NavigationMenu.Alerts.click();
		
		//Filter the app, xbo "New Accounts Assigned" alert
		UI.Alerts.Recipient_textField.sendKeys(parameters.getFullName("approver"));//input ap, xbo
		UI.Alerts.Name_textField.sendKeys(testdata.getInput("alertShortName"));
		UI.Alerts.Apply_link.click();
		
		//Check the total number of filstered result.  (Result 1 - 6 of 6)
		Thread.sleep(5000);
		int totalnumber1 = Integer.parseInt(UI.Alerts.totalNumberOfResults.getText());
		logger.info("totalnumber1 = " + totalnumber1);
		
		
		//Import account
		UI.NavigationMenu.IMPORTS.click();
		UI.NavigationMenu.Import_Data.click();
//		verificationErrors.append(UI.page.VerifyPageTitle(driver, "Import Data from a file"));
		UI.page.selectOptionForDropdownList(UI.ImportData.Import_dropDownList, "Accounts");
		UI.ImportData.Document_textField.sendKeys(accountFilePath);
		UI.ImportData.Import_button.click();
		
		//Verify import successfully.
		if (UI.ImportData.OperationResult.getText().contains("Succeed"))
		{
			logger.info("[Pass!] The importing file operation succeeded!");
		}
		else
		{
			logger.error("[Fail!] The importing file operation failed!");
			verificationErrors.append("[Fail!] The importing file operation failed!");
		}
		
		UI.NavigationMenu.ACCOUNTS.click();
		UI.NavigationMenu.Accounts.click();
		
		//Search the newly imported account
		UI.Accounts.Account_textField.sendKeys(dateString);
		UI.Accounts.Apply_link.click();
		UI.Accounts.Edit_iconOf1stResearchedResult.click();
		
	//Assgin roles to the account
		//Assign Approver role
		UI.AssignmentPage_Accounts.Approver_textField.sendKeys(parameters.getFullName("approver"));
		Thread.sleep(2000);
		UI.AssignmentPage_Accounts.Copyright_text.click();
		
		UI.AssignmentPage_Accounts.Save_button.click();
		Thread.sleep(5000);

		//Alert->Alert Schedule
		UI.NavigationMenu.ALERTS.click();
		UI.NavigationMenu.Alert_Schedule.click();
		
		//Search {New Accounts Assigned Alert} in Batch Name
		UI.AlertSchedule.Batch_Name_textField.sendKeys(testdata.getInput("alertName"));
		UI.AlertSchedule.Apply_link.click();
		UI.AlertSchedule.Edit_iconOfSearchedResult.click();
//		verificationErrors.append(UI.page.VerifyPageTitle(driver, "Alert Schedule"));
		UI.AlertScheduleDetails.Run_Interface_button.click();
		
		
		UI.NavigationMenu.IMPORTS.click();
		UI.NavigationMenu.Import_Status.click();
		
		//Search the account
		UI.ImportStatus.Batch_Name_filterField.sendKeys(testdata.getInput("alertName"));
		UI.ImportStatus.Apply.click();
		
		String Status1 = UI.ImportStatus.Status_of1stSearchedResult.getText();
		String Successful1 = UI.ImportStatus.Successful_of1stSearchedResult.getText();
		
		//Verify the status
		if (Status1.equals("Finished") && Successful1.equals("Yes"))
		{
			logger.info("1st item's status is 'Finished' and successfully field is 'yes'");
		}
		else
		{
			logger.error("1st item's Status should be 'Finished', but is " + Status1 + "; Successfully should be 'Yes', but is " + Successful1);
			verificationErrors.append("1st item's Status should be 'Finished', but is " + Status1 + "; Successfully should be 'Yes', but is " + Successful1);
			
		}
		
		String Status2 = UI.ImportStatus.Status_of2ndSearchedResult.getText();
		String Successful2 = UI.ImportStatus.Successful_of2ndSearchedResult.getText();
		
		if (Status2.equals("Finished") && Successful2.equals("Yes"))
		{
			logger.info("2nd item's status is 'Finished' and successfully field is 'yes'");
		}
		else
		{
			logger.error("2nd item's Status should be 'Finished', but is " + Status2 + "; Successfully should be 'Yes', but is " + Successful2);
			verificationErrors.append("2nd item's Status should be 'Finished', but is " + Status2 + "; Successfully should be 'Yes', but is " + Successful2);
			
		}
		
		//Click "Alerts" ->Alerts link
		UI.NavigationMenu.ALERTS.click();
		UI.NavigationMenu.Alerts.click();
		
		//Filter the app, xbo "New Accounts Assigned" alert
		UI.Alerts.Recipient_textField.clear();//input ap, xbo
		UI.Alerts.Recipient_textField.sendKeys(parameters.getFullName("approver"));//input ap, xbo
		UI.Alerts.Name_textField.clear();
		UI.Alerts.Name_textField.sendKeys(testdata.getInput("alertShortName"));
		UI.Alerts.Apply_link.click();
		
	
		//Check the total number of filstered result.  (Result 1 - 7 of 7)
		//Normally, it takes some time to get the result. So need wait and judge.
		int totalnumber2;
		int i;

		totalnumber2 = Integer.parseInt(UI.Alerts.totalNumberOfResults.getText());
		
		for (i=0; i<20; i++)
		{
			if (totalnumber2 != totalnumber1 + 1)
			{
				logger.info("Currently, totalnumber2 = " + totalnumber2);
				UI.Alerts.Apply_link.click();
				totalnumber2 = Integer.parseInt(UI.Alerts.totalNumberOfResults.getText());
				Thread.sleep(10000);
			}
			else
			{
				logger.info("Currently, totalnumber2 = " + totalnumber2);
				logger.info("[Pass!] The total number of result has been increased 1.");
				break;
			}
		}
		if (i==20)
		{
			logger.error("[Fail!] The total number of results is not increased 1.");
			verificationErrors.append("[Fail!] The total number of results is not increased 1.");
		}
		
		
		//Remove temp file
		cm.deleteFile(("TestData\\" + testdata.getInput("accountFile")));
	
	}

	@After
	public void tearDown() throws Exception {
		CommonMethods.takeScreenShot(this.getClass(), driver);
//		driver.close();
//		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}
}
